#!/usr/bin/env bash
# shellcheck disable=SC1091
# shellcheck disable=SC2009
# Admin https://www.yuque.com/lwmacct

__main() {

    {
        # 判断是否有 docker 和 docker-compose
        if ! command -v docker >/dev/null 2>&1; then
            echo "docker not installed"
            return 1
        fi

        if [[ "$(docker compose version 2>/dev/null | grep version -c)" != "1" ]]; then
            docker run -it --rm --name="install-docker-compose" -v /root/.docker/cli-plugins:/target 1181.s.kuaicdn.cn:11818/pkgs/241122-docker-compose:v2.30.3-x86_64 cp /usr/local/bin/docker-compose /target
        fi

        if [[ "$(docker compose version 2>/dev/null | grep version -c)" != "1" ]]; then
            echo "docker compose not installed"
            return 1
        fi
    }

    {
        # 镜像准备
        _image1="1181.s.kuaicdn.cn:11818/tools/gitrce:categraf-t241123"
        _image2="$(echo "$_image1" | awk -F '/' '{print $NF}')"
        if [[ "$(docker images "$_image2" | wc -l)" != "2" ]]; then
            docker pull $_image1 && docker tag "$_image1" "$_image2"
        fi
    }

    {
        _gre_remote_repo="https://1142.s.kuaicdn.cn:11428/tools-n9e-t241123/master.git"
        _container_name="tools-n9e-t241123"
        _apps_data="/data/kuaicdn/gitrce/$_container_name/master"
        _compose_file="$_apps_data/boot/docker-compose.yaml"
        mkdir -p ${_compose_file%/*}
        cat >$_compose_file <<EOF
services:
  master:
    container_name: $_container_name
    image: $_image2
    restart: always
    network_mode: host
    ipc: host
    uts: host
    privileged: true
    security_opt:
      - apparmor:unconfined
    environment:
      - UPDATE_DATE=20241120-00
      - TINI_SUBREAPER=1
      - GIT_REMOTE_REPO=$_gre_remote_repo
      - APPS_DATA=$_apps_data
      - CONTAINER_NAME=$_container_name
      - HOST_PROC=/hostfs/proc
      - HOST_MOUNT_PREFIX=/hostfs
    volumes:
      - /:/hostfs:ro
      - /run/udev:/run/udev:ro
      - /dev:/dev,rshared
      - /proc/:/host/proc:ro
      - /run/:/host/run:ro
      - /etc:/host/etc:ro
      - /data/:/data:rw
      - /disk/:/disk:rw,shared
      - "$_apps_data/:/apps/data"
EOF

    }

    {
        # run
        docker ps -f name="[0-9a-z]{12}_$_container_name" -aq | xargs -r docker rm -f # 删除变种容器
        _cmd="docker compose -p $_container_name -f $_compose_file up -d --remove-orphans"
        if ! eval "$_cmd"; then
            docker ps -f name=$_container_name -aq | xargs -r -I{} echo 'ps -ef | grep -v $$ |  grep {}' | sh | awk '{print $2}' | xargs -r -I{} kill -9 {}
            docker rm -f $_container_name
            eval "$_cmd"
        fi
    }

}

__main

: <<!
    curl -sSL https://1142.s.kuaicdn.cn:11428/tools-n9e-t241123/master/raw/branch/main/boot/install.sh | bash
!